package org.jwos.platform.service.internal;

import java.util.Hashtable;

import org.jwos.platform.domain.GlobalConfig;
import org.jwos.platform.domain.GlobalSession;
import org.jwos.platform.domain.User;
import org.jwos.platform.service.SessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StubSessionManager implements SessionManager {
	
	private Hashtable sessions = new Hashtable();
	
	private GlobalConfig globalConfig;
	
	@Autowired
	private void setGlobalConfig(GlobalConfig globalConfig) {
		this.globalConfig = globalConfig;
	}

	public User getUserBySessionId(String sessionId) {
		User user = null;
		
		if(sessionId!=null && sessions.containsKey(sessionId)) {
			GlobalSession session = (GlobalSession)this.sessions.get(sessionId);
			user = session.getUser();
		}
		
		return user;
	}

	public void registerSession(String sessionId, User user) {
		if(this.sessions.containsKey(sessionId)) {
			this.sessions.remove(sessionId);
		}
		
		GlobalSession session = new GlobalSession();
		session.setSessionId(sessionId);
		session.setUser(user);
		this.sessions.put(sessionId, session);
	}

	public void unregisterSession(String sessionId) {
		this.sessions.remove(sessionId);
	}
	
	public Object getAttribute(String sessionId,String name) {
		Object value = null;
		
		if(sessionId!=null && this.sessions.containsKey(sessionId)) {
			GlobalSession session = (GlobalSession)this.sessions.get(sessionId);
			value = session.getAttribute(name);
		}
		
		return value;
	}
	
	public void setAttribute(String sessionId,String name,Object value) {
		if(sessionId!=null && this.sessions.containsKey(sessionId)) {
			GlobalSession session = (GlobalSession)this.sessions.get(sessionId);
			session.setAttribute(name, value);
		}
	}
	
	public void removeAttribute(String sessionId,String name) {
		if(sessionId!=null && this.sessions.containsKey(sessionId)) {
			GlobalSession session = (GlobalSession)this.sessions.get(sessionId);
			session.removeAttribute(name);
		}
	}
	
	public GlobalSession getGlobalSession(String sessionId) {
		if(sessionId!=null) {
			return (GlobalSession)this.sessions.get(sessionId);
		} else {
			return null;
		}
	}
	
	public GlobalConfig getGlobalConfig() {
		return this.globalConfig;
	}
}
